package com.efast.dmom.equipment.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.efast.cafe.commponent.log.ext.CafeLogger;
import com.efast.cafe.commponent.log.ext.CafeLoggerFactory;
import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.constant.CommonConstant;
import com.efast.cafe.framework.enums.ResultStatus;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.redis.locker.annotation.CafeLock;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.cafe.util.StringValidationUtils;
import com.efast.dmom.equipment.api.WechatPhoneBindingControllerApi;
import com.efast.dmom.equipment.bean.PhoneBindingBean;
import com.efast.dmom.equipment.service.wechat.impl.WechatPhoneBindingService;

import jodd.util.StringUtil;

@Controller
@RequestMapping("/equipment")
public class EquipPhoneBindingController implements WechatPhoneBindingControllerApi {

	CafeLogger logger = CafeLoggerFactory.getLogger(getClass());

	@Autowired
	private StringRedisTemplate redisTemplate;
	
	@Autowired
	private WechatPhoneBindingService bindingService;
	

	@Override
	@RequestMapping(value = "/wechat/sendMns", method = RequestMethod.POST)
	public @ResponseBody ResultBean sendMns(@RequestBody PhoneBindingBean code) {
		return generateMnsCode(code.getPhone());
	}
	
	@Override
	@RequestMapping(value = "/wechat/bindingPhone", method = RequestMethod.POST)
	public @ResponseBody ResultBean bindingPhone(@RequestBody PhoneBindingBean bindingBean) {
		
		ResultBean res = new ResultBean(true);
		
		String openId = (String) SpringWebUtils.getSession().getAttribute(CommonConstant.WECHAT_OPENID);
		String phoneNumber = bindingBean.getPhone();
		
//		boolean valid = StringValidationUtils.checkMobile(phoneNumber);
//		if(!valid) {
//			res.setErrorCode(ResultStatus.PARAM_ERROR.getCode());
//			res.setMessage("请输入正确的手机号码");
//			res.setSuccess(false);
//			return res;
//		}
		String key = new StringBuilder("mns:hm:").append(phoneNumber).toString();
		
		String mnsCodeServer = redisTemplate.opsForValue().get(key);
		if(mnsCodeServer == null || "".equals(mnsCodeServer)){
			res.setErrorCode(ResultStatus.PARAM_ERROR.getCode());
			res.setMessage("输入验证码超时");
			res.setSuccess(false);
			return res;
		}
		
		String mnsCodeClient = bindingBean.getMnsCode();
		if(! mnsCodeServer.equals(mnsCodeClient)){
			res.setErrorCode(ResultStatus.PARAM_ERROR.getCode());
			res.setMessage("输入验证码错误");
			res.setSuccess(false);
			return res;
		}
		
		bindingService.bindPhone(phoneNumber, openId);
		
		SpringWebUtils.getSession().setAttribute(CommonConstant.WECHAT_OPENID, null);
		
		res.setMessage("綁定成功");
		return res;
	}

	@CafeLock(name = "locker:hm_mns:", keyGroup = "Portal", waitTime = 1, keys = { "{#phone}" }, leaseTime = 60)
	private ResultBean generateMnsCode(String phone) {
		ResultBean res = new ResultBean(true);
//		if (!StringValidationUtils.checkMobile(phone)) {
//			throw new ServiceException(ResultStatus.PARAM_ERROR.getCode(), "手机号码输入错误");
//		}

		String key = new StringBuilder("mns:hm:").append(phone).toString();
		if (redisTemplate.hasKey(key)) {
			res.setErrorCode(ResultStatus.DATA_REPEAT_ER.getCode());
			res.setMessage("请勿重复发送验证码");
			res.setSuccess(false);
			return res;
		}
		int random = (int) ((Math.random() * 9 + 1) * 10000);
		Map<String, String> params = new HashMap<String, String>();
		params.put("code", random + "");
		redisTemplate.opsForValue().set(key, random + "", 50, TimeUnit.SECONDS);

		res.setObject(random + "");
		return res;
	}

}
